<script lang="ts" setup>
import { cloneDeep } from 'lodash-es';
import { onMounted, reactive, ref, watch } from 'vue';
import { MinusCircleFilled, PlusCircleFilled } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue/es';
import { useRoute, useRouter } from 'vue-router';
import { useNewExcelStore } from '@/store/modules/dcp/assessment_indicators/new_excel';

const router = useRouter();

const columns = ref<any[]>([
  {
    title: '表头名称（header）',
    dataIndex: 'paramsName',
    width: '20%',
    align: 'center',
  },
  {
    title: '关键字（key）',
    dataIndex: 'paramsKey',
    width: '20%',
    align: 'center',
  },
  {
    title: '操作',
    width: '12%',
    dataIndex: 'operation',
    align: 'center',
  },
]);

// 字段保存的数据
const editTable = reactive<any>({
  1: {
    id: '1',
    paramsName: '',
    paramsKey: '',
  },
});

// 表格默认数据
const dataSource = ref<AAPI.NewExcelDataItem[]>([
  {
    id: '1',
    paramsName: '',
    paramsKey: '',
  },
]);

const currNextName = ref<HTMLElement>();

const currNextKey = ref<HTMLElement>();

// 获取新建表的title和name
const title = ref<string>('');
const sheetName = ref<string>('');
const route = useRoute();
onMounted(() => {
  if (route.query.title) {
    title.value = route.query.title as string;
  }
  else {
    title.value = useNewExcelStore().getTitle();
  }
  if (route.query.name) {
    sheetName.value = route.query.name as string;
  }
  else {
    sheetName.value = useNewExcelStore().getSheetName();
  }

  // 初始化默认值
  currNextName.value = document.querySelector(`.name${dataSource.value[0].id}`) as HTMLElement;
  currNextKey.value = document.querySelector(`.key${dataSource.value[0].id}`) as HTMLElement;
});

// 监听input框的focus事件，消除未填写提示
watch(currNextName, (nv) => {
  nv?.addEventListener('focus', () => {
    nv.style.borderColor = '';
    nv.style.boxShadow = '';
  });
});

watch(currNextKey, (nv) => {
  nv?.addEventListener('focus', () => {
    nv.style.borderColor = '';
    nv.style.boxShadow = '';
  });
});

function handleField(val: string, record: any) {
  if (val === 'add') {
    if (editTable[record.id].paramsName === '') {
      nextTick(() => {
        const currName = document.querySelector(`.name${record.id}`) as HTMLInputElement;
        currName.style.borderColor = 'var(--polar-error-color-hover)';
        currName.style.boxShadow = '0 0 0 1px #F59B9B';
      });
      return message.error('表头名称不能为空！');
    }
    if (editTable[record.id].paramsKey === '') {
      nextTick(() => {
        const currAlias = document.querySelector(`.key${record.id}`) as HTMLInputElement;
        currAlias.style.borderColor = 'var(--polar-error-color-hover)';
        currAlias.style.boxShadow = '0 0 0 1px #F59B9B';
      });
      return message.error('关键字不能为空！');
    }
    for (const item in editTable) {
      if (editTable[item].paramsName === '') {
        nextTick(() => {
          if (currNextName.value) {
            currNextName.value.style.borderColor = 'var(--polar-error-color-hover)';
            currNextName.value.style.boxShadow = '0 0 0 1px #F59B9B';
          }
        });
        return message.error('表头名称不能为空！');
      }
      if (editTable[item].paramsKey === '') {
        nextTick(() => {
          if (currNextKey.value) {
            currNextKey.value.style.borderColor = 'var(--polar-error-color-hover)';
            currNextKey.value.style.boxShadow = '0 0 0 1px #F59B9B';
          }
        });
        return message.error('关键字不能为空！');
      }
    }
    const obj = {
      id: new Date().getTime().toString(),
      paramsName: '',
      paramsKey: '',
    };
    editTable[obj.id] = cloneDeep(obj);
    dataSource.value.push({ id: obj.id });
    nextTick(() => {
      currNextName.value = document.querySelector(`.name${obj.id}`) as HTMLInputElement;
      currNextKey.value = document.querySelector(`.key${obj.id}`) as HTMLInputElement;
    });
  }
  else {
    // 删除行
    if (record.id === '1') {
      return;
    }
    const currIndex = dataSource.value.findIndex(item => item.id === record.id);
    if (currIndex !== -1) {
      dataSource.value.splice(currIndex, 1);
    }
    delete editTable[record.id];
  }
}

// 保存
let header: any[] = [];

async function getHeader() {
  header = [];
  for (const key in editTable) {
    const nestedObj = editTable[key];
    header.push({ header: nestedObj.paramsName, key: nestedObj.paramsKey, width: 20 });
  }
}

async function saveExcel() {
  await getHeader();
  const newExcelStore = useNewExcelStore();
  newExcelStore.setExcelHeader(header, title.value, sheetName.value);
  router.push('/assessment_indicators/newexcelbody');
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            新建表头:{{ sheetName }}
          </div>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="saveExcel">
            保存
          </a-button>
          <!-- <a-button type="primary" @click="$router.push('/assessment_indicators/quarter');">
            返回
          </a-button> -->
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table :columns="columns" :data-source="dataSource" bordered :pagination="false" class="edit-table">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'paramsName'">
            <a-input
              v-model:value="editTable[record.id][column.dataIndex]" :placeholder="`${column.title}`"
              :class="`name${record.id}`"
            />
          </template>
          <template v-if="column.dataIndex === 'paramsKey'">
            <a-input
              v-model:value="editTable[record.id][column.dataIndex]" :placeholder="`${column.title}`"
              :class="`key${record.id}`"
            />
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <PlusCircleFilled
              style="margin-right: 5px;font-size: 16px;color: #52c41a;"
              @click="handleField('add', record)"
            />
            <MinusCircleFilled style=" font-size: 16px;color: #ff4d4f;" @click="handleField('delete', record)" />
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .edit-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}
</style>
